package gui;

import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

import model.Stack;

/**
 * @author Alexander Shidlovsky
 */
public abstract class TabledFilteringPanel extends JPanel implements Updatable {
	private JTable tbl;
	private DefaultTableModel model;
	protected Vector<String> columnNames = new Vector<String>();
	protected Vector<Vector<Object>> data = new Vector<Vector<Object>>();

	public TabledFilteringPanel() {

		model = new DefaultTableModel();
		setLayout(new BorderLayout(0, 0));

		tbl = new JTable(model) {
			@Override
			public boolean isCellEditable(int rowIndex, int colIndex) {
				return false; // Disallow the editing of any cell
			}
		};

		tbl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		JScrollPane scrollPane = new JScrollPane(tbl);

		add(scrollPane);

		tbl.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent event) {
				if (event.getClickCount() == 2) {
					int index = tbl.getSelectedRow();
					Stack stack = (Stack) tbl.getModel().getValueAt(index, 0);
					if (stack != null) {
						StackInfoDialog info = new StackInfoDialog(stack);
						info.setVisible(true);
					}
				}
			}
		});
	}

	public void setData(Vector<String> columnNames, Vector<Vector<Object>> data) {
		this.columnNames = columnNames;
		this.data = data;
		DefaultTableModel newModel = new DefaultTableModel(this.data,
				this.columnNames);
		tbl.setModel(newModel);
	}

	@Override
	public void updateView() {
		int index = tbl.getSelectedRow();
		data.clear();
		generateDataVector();
		((DefaultTableModel) tbl.getModel()).fireTableDataChanged();
		if ((tbl.getRowCount() > index) && (index > -1)) {
			tbl.setRowSelectionInterval(index, index);
		}
	}

	protected abstract void generateDataVector();

	// Get methods for data and column names

}
